package com.whale.service.impl;



import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whale.constant.MessageConstant;
import com.whale.dto.GoodsPageQueryDTO;
import com.whale.entity.Goods;
import com.whale.mapper.GoodsMapper;
import com.whale.result.PageResult;
import com.whale.result.ResponseResult;
import com.whale.service.GoodsService;
import com.whale.vo.GoodsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 添加商品
     * @param goods
     * @return
     */
    public ResponseResult addGoods(Goods goods){
        if(ObjectUtil.isEmpty(goods)){
            return ResponseResult.errorResult(0, MessageConstant.GOODS_IS_EMPTY);
        }
        save(goods);
        return ResponseResult.okResult(1,MessageConstant.GOODS_ADD_SUCCESS);
    }

    /**
     * 商品条件分页查询
     * @param goodsPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(GoodsPageQueryDTO goodsPageQueryDTO) {
        LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<>();

        if(ObjectUtil.isNotNull(goodsPageQueryDTO.getCategoryId())){
            lambdaQueryWrapper.eq(Goods::getCategoryId,goodsPageQueryDTO.getCategoryId() );
            }
        if(ObjectUtil.isNotNull(goodsPageQueryDTO.getName())){
            lambdaQueryWrapper.like(Goods::getName,goodsPageQueryDTO.getName());
        }
        if(ObjectUtil.isNotNull(goodsPageQueryDTO.getStatus())) {
            lambdaQueryWrapper.eq(Goods::getStatus,goodsPageQueryDTO.getStatus() );
        }
        Page<Goods> page=new Page<>(goodsPageQueryDTO.getPage(),goodsPageQueryDTO.getPageSize());
        page(page,lambdaQueryWrapper);
        Long total=page.getTotal();
        List<Goods> goodsList=page.getRecords();
        List<GoodsVO> goodsVOList = goodsList.stream().map(goods -> {
            GoodsVO goodsVO=new GoodsVO();
            BeanUtils.copyProperties(goods,goodsVO);
            return goodsVO;
        }).collect(Collectors.toList());
        return new PageResult(total,goodsVOList);
    }
    }




